package framework.api;

import framework.impl.MinimalPomParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

public interface PomModel {

    String NATIVE_MAVEN_PARSER_CLASS = "org.kie.scanner.MavenPomModelGenerator";

    ReleaseId getReleaseId();

    class InternalModel implements PomModel {
        private ReleaseId releaseId;
        @Override
        public ReleaseId getReleaseId() {
            return releaseId;
        }

    }

    class Parser {

        private static final Logger log = LoggerFactory.getLogger(PomModel.class);
        private static class PomModelGeneratorHolder {
            private static PomModelGenerator pomModelGenerator;

            static {
                try {
                    pomModelGenerator = (PomModelGenerator) Class.forName(NATIVE_MAVEN_PARSER_CLASS).newInstance();
                } catch (Exception e) {
                    pomModelGenerator = new DefaultPomModelGenerator();
                }
            }
        }

        public static PomModel parse(String path, InputStream is) {
            try {
                return PomModelGeneratorHolder.pomModelGenerator.parse(path, is);
            } catch (Exception e) {
                if (PomModelGeneratorHolder.pomModelGenerator.getClass().getName().equals(NATIVE_MAVEN_PARSER_CLASS) && isOpen(is)) {
                    log.warn("Error generated by the maven pom parser, falling back to the internal one", e);
                    return MinimalPomParser.parse(path, is);
                }
                if (e instanceof RuntimeException) {
                    throw (RuntimeException)e;
                } else {
                    throw new RuntimeException(e);
                }
            }
        }

        private static boolean isOpen(InputStream is) {
            try {
                return is.available() > 0;
            } catch (IOException ioe) {
                return false;
            }
        }
    }

    class DefaultPomModelGenerator implements PomModelGenerator {
        @Override
        public PomModel parse(String path, InputStream is) {
            return MinimalPomParser.parse(path, is);
        }
    }
}
